this.name        = "deep_space_dredger"; 
this.author      = "eric walch"; 
this.copyright   = "� 2008 Walch & Sabre & Little Bear"; 
this.description = "This script places the dredgers in deep space."; 
this.version     = "2.2.5"; 

this.startUp = this.reset = function() {
    this.dredger = true;
    if (this.dredgerTimer) {
        this.dredgerTimer.start();
    } else {
        this.dredgerTimer = new Timer(this, this.dredgerCheck, 150, 120);
	}
};

this.shipExitedWitchspace = function()
{
    if(this.salvageList) {delete this.salvageList; delete this.salvageNameList}
    if(System.isInterstellarSpace || System.sun.hasGoneNova) return;
	this.dredger = false
    if(System.techLevel > 8)
	{
		if(Math.random() < 0.5)
		{
			if(Math.random() < 0.2) System.legacy_addShipsAt("dredgertrader", 1, "pwu", [0.0, 0.0, 0.1+Math.random()*0.8])
			this.dredger = true;
		}
		else
		{
			if(Math.random() < 0.05 && !worldScripts["bigShips_populator"]) 
				System.legacy_addShipsAt("dredgers", 1, "pwp", [Math.random(), Math.random(), 3+7*Math.random()])
			// witchpoint is at 10 to 14 planet radii from planet
		}
	}
	if(System.government < Math.random()*7) // more change in low governments
	{
		if(Math.random() < 0.2) this.addDerelict(0.1+Math.random()*0.8)
		if(Math.random() < 0.2) this.addDerelict(0.1+Math.random()*0.8)
		if(Math.random() < 0.02)
		{
			var location = Math.ceil(Math.random()*5)
			switch(location)
			{
			case 1:   { System.legacy_addSystemShips("dredgerDerelict", 5, 0.97)  // 20%
				player.commsMessage(expandDescription("[salvage_drone_battle_station]"), 6); break}
			case 5:    {System.legacy_addSystemShips("dredgerDerelict", 5, 0)   // 20%
				player.commsMessage(expandDescription("[salvage_drone_battle_witchpoint]"), 6); break}
			default:    {System.legacy_addSystemShips("dredgerDerelict", 5, 0.2+Math.random()*0.7)   // 60%
				player.commsMessage(expandDescription("[salvage_drone_battle_spacelane]"), 6); break}
			}
			this.dredger = true
		}
	}
}

this.addDerelict = function(location)
{
	if(!System.mainStation) return;
	var derelict = System.mainStation.spawnOne("trader")
		derelict.switchAI("dredgersDerelictAI.plist")
		derelict.bounty = 0
		if (0 < oolite.compareVersion("1.73")) 
			derelict.setPosition(Vector3D.interpolate([0,0,0], System.mainPlanet.position, location).add(Vector3D.randomDirectionAndLength(10E3)))
		else derelict.position = Vector3D.interpolate([0,0,0], System.mainPlanet.position, location).add(Vector3D.randomDirectionAndLength(10E3));
		derelict.script.derelictInitialisation = this.dredgerDerelictInitialisation
}

// next script becomes attached to the derelict ship-script. This to assure self modifying trader scripts are not affected.
this.dredgerDerelictInitialisation = function()
{
	this.ship.primaryRole = "dredgerDerelict"
	this.ship.displayName = this.ship.displayName + " (derelict)"
}

this.dredgerCheck = function()
{
    if(this.dredger && player.ship.speed > player.ship.maxSpeed && !System.isInterstellarSpace && player.ship.position.distanceTo(System.mainPlanet.position) > 1.5E6) 
    { 
        this.addDredger(); 
        if(Math.random()< 0.5) this.dredger = false 
    }
}

this.addDredger = function()
{
    var orientation = player.ship.orientation; 
    var forwardPosition = player.ship.position.add(orientation.vectorForward().multiply(300E3))
    System.legacy_addShipsAtPrecisely("dredgers", 1, "abs", forwardPosition)
    if(Math.random()<0.5) 
    {
        System.legacy_addShipsWithinRadius("asteroid", Math.ceil(Math.random()*3), "abs", forwardPosition, 10E3)
        System.legacy_addShipsWithinRadius("miner", Math.ceil(Math.random()*3), "abs", forwardPosition, 10E3)
    }
}

// Below are functions used by ships
this.checkSalvage = function(ship)
{
    if(!this.salvageList) return false;
    if(this.salvageList.indexOf(ship) > -1) return true;
    return false;
}

this.addSalvage = function(ship)
{
    if(!this.salvageList)
    {
        this.salvageList = [ship];
        this.salvageNameList = [ship.displayName];
        return true;
    }
    if(this.salvageList.indexOf(ship) > -1) return false;
    this.salvageList.push(ship)
    this.salvageNameList.push(ship.displayName);
    return true;
}

this.removeSalvage = function(ship)
{
    if(!this.salvageList) return false;
    var i = this.salvageList.indexOf(ship)
    if(i> -1)
    {
        this.salvageList.splice(i,1)
        this.salvageNameList.splice(i,1)
        return true;
    }
    return false;
}

this.startScanner = function(salvager) // activated by dredgerscript
{
	this.salvageShip = salvager;
	this.timerCount = 0;
    if(this.salvageTimer)
        this.salvageTimer.start()
    else
        this.salvageTimer = new Timer(this, this.scanSalvage, 15, 15)
}

this.playerWillEnterWitchspace = function() {
    if (this.dredgerTimer) {
		this.dredgerTimer.stop();
		delete this.dredgerTimer;
	}
    if (this.salvageTimer) {
		this.salvageTimer.stop();
		delete this.salvageTimer;
	}
};

this.scanSalvage= function()
{
    if(!this.salvageList || this.salvageList.length == 0 || !this.salvageShip.isValid) {
		if(this.salvageTimer) {
			this.salvageTimer.stop();
			delete this.salvageTimer;
		}
	}
    for (var i=0; i<this.salvageList.length;i++)
    {
        if(!this.salvageList[i].isValid)  // if ship died.
        {
            this.salvageList.splice(i,1)
            var lostShipName = this.salvageNameList.splice(i,1)
            player.commsMessage(expandDescription("[salvage_drone_intro] ") + this.salvageShip.displayName + expandDescription(" [salvage_drone_killed] ") + lostShipName, 6);
			return;
        }
    }
	if(this.timerCount++ > 10)
	{
		player.consoleMessage(expandDescription("[salvage_drone_intro] ") + this.salvageShip.displayName + " is still waiting for incoming " + this.salvageNameList[0], 6);
		this.timerCount = 0;
	}
}

// Below are scripts attached by missile-script to the derelict ships
this.derelictDied = function(ship)
{
	var cargo = Math.ceil(Math.random()*10)
	if(ship.availableCargoSpace < cargo) cargo = ship.availableCargoSpace
	if(cargo > 0) ship.spawn("cargopod", (Math.random()*5+5))
}

this.derelictDocked = function(station)
{
    if(worldScripts.deep_space_dredger.checkSalvage(this.ship))
    {
        var cargo = Math.round(this.ship.availableCargoSpace/2.5*Math.random())
        var payment = Math.round(this.ship.mass/1000)*10 + cargo * 13;
        if(this.ship.bounty > 0) payment *= 1.5  // give a 50% bonus for criminal ships.
        missionVariables.salvage_drone_award = payment
        missionVariables.salvage_drone_cargo = cargo
        missionVariables.salvage_drone_dname = station.displayName
        missionVariables.salvage_drone_wname = this.ship.name
        player.commsMessage(expandDescription("[salvage_drone_congrats]"), 6) // should always reach player.
        player.credits += payment;
        missionVariables.salvage_drone_award = null
        missionVariables.salvage_drone_cargo = null
        missionVariables.salvage_drone_dname = null
        missionVariables.salvage_drone_wname = null
        worldScripts.deep_space_dredger.removeSalvage(this.ship) // remove from the approach list in the main script.
    }
}